﻿using System.Collections.Generic;
using System.Web.Http.Controllers;
using System.Web.Http.Filters;
using System.Web.Http.ModelBinding;
using System.Text;

/// <summary>
/// 
/// </summary>
public class ModelValidationFilterAttribute : ActionFilterAttribute
{
    /// <summary>
    /// 
    /// </summary>
    /// <param name="actionContext"></param>
    public override void OnActionExecuting(HttpActionContext actionContext)
    {
        if (actionContext.ModelState.IsValid == false)
        {
            var errors = new List<string>();
            foreach (KeyValuePair<string, ModelState> keyValue in actionContext.ModelState)
            {
                StringBuilder sb = new StringBuilder();
                foreach (var item in keyValue.Value.Errors)
                {
                    if (!string.IsNullOrEmpty(item.ErrorMessage))
                        sb.AppendLine(item.ErrorMessage);
                    if (item.Exception != null)
                        sb.AppendLine(item.Exception.Message); 
                }

                if(sb.Length>0)
                    errors.Add(sb.ToString());
            }

            //ErrorResultEnum validEnum = ErrorResultEnum.ModelIsValid;

            //NullResponseModel model = new NullResponseModel();
            //model.Status = ResponseEnums.Status.Failure;
            //model.Meta.Message = validEnum.GetEnumDescription();
            //model.Meta.Code = validEnum.GetEnumValue();
            //model.Meta.ValidationErrors = errors;
            //actionContext.Response =actionContext.Request.CreateResponse(HttpStatusCode.BadRequest, model);
        }
    }
}